﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.Collections.Specialized;
using Microsoft.SharePoint.Utilities;

namespace WebpartSample
{
    class ListTimerJob : SPJobDefinition
    {
        public ListTimerJob()
            : base()
        {

        }

        public ListTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
            : base(jobName, service, server, targetType)
        {

        }

        public ListTimerJob(string jobName, SPWebApplication webApplication)
            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
        {
            this.Title = "List Timer Job";

        }

        public override void Execute(Guid contentDbId)
        {
            // get a reference to the current site collection's content database
            SPWebApplication webApplication = this.Parent as SPWebApplication;
            SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
            // get a reference to the "ListTimerJob" list in the RootWeb of the first site collection in the content database
            SPQuery camQ = new SPQuery();
            camQ.Query = "<Where><Eq><FieldRef Name=\"when_x0020_to_x0020_send\" /><Value Type=\"DateTime\">[Today+10Day(s)]</Value></Eq></Where>";
            SPListItemCollection Listjob = contentDb.Sites[0].RootWeb.Lists["ListTimerJob"].GetItems(camQ);
            // create a new list Item, set the Title to the current day/time, and update the item
            StringDictionary headers = new StringDictionary();

            headers.Add("from", "livingston@triadinfotech.com");
            headers.Add("to", "liviggl@gmail.com");
            headers.Add("subject", "<subject> "+DateTime.Now.ToShortTimeString());
            headers.Add("content-type", "text/html"); //This is the default type

            System.Text.StringBuilder strMessage = new System.Text.StringBuilder();
            strMessage.Append(string.Format("<b>{0}</b><br /><img src=\"\"/>",
            webApplication.Sites[0].RootWeb.Lists["ListTimerJob"].Items[0].ToString()));
            /*
             stsadm -o email 
             -outsmtpserver mail.triadinfotech.com 
             -replytoaddress livingston@triadinfotech.com 
             -fromaddress livingston@triadinfotech.com 
             -codepage 65001 
             -url http://triad125:22329
            */
            SPUtility.SendEmail(contentDb.Sites[0].RootWeb, headers, strMessage.ToString());
        }
    }
}
